import os
import sys
from bs4 import BeautifulSoup
from html2docx import html2docx


def html_to_word(html_path, output_path=None, encoding='utf-8'):
    """
    将HTML文件转换为Word文档

    参数:
        html_path: HTML文件的路径
        output_path: 输出Word文档的路径，默认为原HTML文件同目录下的同名.docx
        encoding: HTML文件的编码格式，默认为utf-8
    """
    # 验证输入文件是否存在
    if not os.path.exists(html_path):
        raise FileNotFoundError(f"HTML文件不存在: {html_path}")

    # 设置默认输出路径
    if output_path is None:
        file_name = os.path.splitext(os.path.basename(html_path))[0]
        output_path = os.path.join(os.path.dirname(html_path), f"{file_name}.docx")

    try:
        # 读取HTML内容
        with open(html_path, 'r', encoding=encoding) as f:
            html_content = f.read()

        # 使用BeautifulSoup解析HTML（可选，用于预处理）
        soup = BeautifulSoup(html_content, 'html.parser')

        # 可选：预处理HTML，例如移除不需要的标签
        # 示例：移除所有<script>标签
        for script in soup(["script", "style"]):
            script.decompose()

        # 使用库函数将HTML转换为docx的字节流
        file_name = os.path.splitext(os.path.basename(html_path))[0]
        buf = html2docx(str(soup), title=file_name)

        # 将字节流写入目标路径
        with open(output_path, 'wb') as out_fp:
            out_fp.write(buf.getvalue())
        print(f"转换成功！Word文档已保存至: {output_path}")

        return output_path

    except Exception as e:
        print(f"转换失败: {str(e)}")
        return None


if __name__ == "__main__":
    # 允许通过命令行传入参数：python html2word.py <html_path> [output_path]
    script_dir = os.path.dirname(os.path.abspath(__file__))
    default_html = os.path.join(script_dir, "笔录.html")

    if len(sys.argv) >= 2:
        html_file = sys.argv[1]
    else:
        html_file = default_html if os.path.exists(default_html) else os.path.join(script_dir, "input.html")

    output_file = sys.argv[2] if len(sys.argv) >= 3 else None

    html_to_word(html_file, output_file)